import {
  View,
  Text,
  StyleSheet,
  TextInput,
  Pressable,
  Alert,
  Button,
} from "react-native";
import React, { useEffect, useState } from "react";
import Icon from "react-native-vector-icons/FontAwesome";
import { NativeStackNavigationProp } from "@react-navigation/native-stack";
import HeaderBack from "../../components/HeaderBack";

import { registerApi } from "../../api/user";

type Props = {
  navigation: NativeStackNavigationProp<any>;
};

export default function Register({ navigation }: Props) {
  navigation.setOptions({
    headerLeft(props) {
      return <HeaderBack props={props} />;
    },
    headerRight: () => (
      <Button title="帮助" color={"#666"} onPress={() => {}} />
    ),
  });

  const [name, setName] = useState("");
  const [email, setEmail] = useState("");
  const [phone, setPhone] = useState("");
  const [password, setPassword] = useState("");
  const [rePassword, setRePassword] = useState("");
  const [isShowPwd, setIsShowPwd] = useState(false);
  const [isShowRePwd, setIsShowRePwd] = useState(false);
  const [isOkRegister, setIsOkRegister] = useState(false);

  useEffect(() => {
    if (name && email && phone && password && rePassword) {
      setIsOkRegister(true);
    } else {
      setIsOkRegister(false);
    }
  }, [name, email, phone, password, rePassword]);

  async function register() {
    if (!isOkRegister) return;
    const pattern = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
    const regex = /^1[3-9]\d{9}$/;
    console.log(email);

    if (name.length < 3 || name.length > 8) {
      Alert.alert("用户名长度为3-8位");
      return;
    }
    if (!pattern.test(email)) {
      Alert.alert("邮箱格式错误");
      return;
    }
    if (!regex.test(phone)) {
      Alert.alert("手机号格式错误");
      return;
    }

    if (password.length < 8 || password.length > 16) {
      Alert.alert("密码长度为8-16位");
      return;
    }
    if (password !== rePassword) {
      Alert.alert("两次密码输入不一致");
      return;
    }

    // 数据验证通过
    const res = await registerApi({
      name,
      phone,
      email,
      password,
    });
    if (res.code == 200) {
      Alert.alert("注册成功", "", [
        {
          text: "确定",
          onPress: () => {
            setName("");
            setEmail("");
            setPhone("");
            setPassword("");
            setRePassword("");
            navigation.navigate("Login");
          },
        },
      ]);
    } else {
      Alert.alert(res.message);
    }
    console.log(res);
  }

  return (
    <>
      <View style={styles.container}>
        <View style={styles.title}>
          <Text style={styles.tip}>注册</Text>
          <Text style={styles.desc}>
            即可开启您的全新体验，让我们一起共享精彩世界。
          </Text>
        </View>
        <View style={styles.box}>
          <View style={styles.email}>
            <TextInput
              style={styles.emailInput}
              placeholder="请输入用户名"
              value={name}
              onChangeText={(text) => setName(text)}
            ></TextInput>
          </View>
          <View style={styles.email}>
            <TextInput
              style={styles.emailInput}
              placeholder="请输入邮箱"
              value={email}
              onChangeText={(text) => setEmail(text)}
            ></TextInput>
          </View>
          <View style={styles.email}>
            <TextInput
              style={styles.emailInput}
              placeholder="请输入手机号码"
              value={phone}
              onChangeText={(text) => setPhone(text)}
            ></TextInput>
          </View>
          <View style={styles.password}>
            <TextInput
              style={styles.passwordInput}
              secureTextEntry={!isShowPwd}
              placeholder="请输入密码"
              value={password}
              onChangeText={(text) => setPassword(text)}
            ></TextInput>
            <Pressable
              onPress={() => {
                setIsShowPwd(!isShowPwd);
              }}
            >
              {!isShowPwd ? (
                <Icon name="eye-slash" size={22} color="#333"></Icon>
              ) : (
                <Icon name="eye" size={22} color="#333"></Icon>
              )}
            </Pressable>
          </View>
          <View style={styles.password}>
            <TextInput
              style={styles.passwordInput}
              secureTextEntry={!isShowRePwd}
              placeholder="请输入确认密码"
              value={rePassword}
              onChangeText={(text) => setRePassword(text)}
            ></TextInput>
            <Pressable
              onPress={() => {
                setIsShowRePwd(!isShowRePwd);
              }}
            >
              {!isShowRePwd ? (
                <Icon name="eye-slash" size={22} color="#333"></Icon>
              ) : (
                <Icon name="eye" size={22} color="#333"></Icon>
              )}
            </Pressable>
          </View>
          <Pressable
            onPress={() => {
              register();
            }}
          >
            <View
              style={[
                styles.login,
                { backgroundColor: isOkRegister ? "#12b886" : "#efefef" },
              ]}
            >
              <Text
                style={[
                  styles.loginText,
                  { color: isOkRegister ? "#fff" : "#999" },
                ]}
              >
                注 册
              </Text>
            </View>
          </Pressable>
        </View>
        <View style={styles.agreement}>
          <Text style={{ fontSize: 12 }}>注册代表您已阅读并同意</Text>
          <Text style={{ fontSize: 12, color: "red", marginLeft: 5 }}>
            《用户协议》
          </Text>
        </View>
      </View>
    </>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    // justifyContent: 'center',
    // alignItems: 'center',
    backgroundColor: "#fff",
  },
  title: {
    justifyContent: "center",
    alignItems: "center",
  },
  tip: {
    fontSize: 20,
    fontWeight: "bold",
    color: "#000",
    paddingTop: 10,
    paddingBottom: 10,
  },
  desc: {
    fontSize: 12,
    color: "#999",
  },
  box: {
    padding: 30,
  },
  email: {
    borderBottomWidth: 1,
    borderBottomColor: "#efefef",
    paddingBottom: 10,
    marginBottom: 10,
  },
  emailInput: {
    fontSize: 16,
    color: "#000",
  },
  password: {
    borderBottomWidth: 1,
    borderBottomColor: "#efefef",
    paddingBottom: 10,
    marginBottom: 10,
    flexDirection: "row",
    justifyContent: "space-between",
    alignItems: "center",
  },
  passwordInput: {
    fontSize: 16,
    color: "#000",
    height: 32,
    flex: 1,
  },
  forget: {
    flexDirection: "row",
    justifyContent: "space-between",
    alignItems: "flex-end",
  },
  forgetText: {
    fontSize: 13,
    color: "#333",
    marginTop: 4,
    paddingBottom: 4,
  },
  login: {
    backgroundColor: "#efefef",
    height: 44,
    justifyContent: "center",
    alignItems: "center",
    borderRadius: 20,
    marginTop: 10,
  },
  loginText: {
    fontSize: 16,
    color: "#999",
    fontWeight: "bold",
  },
  agreement: {
    flex: 1,
    marginTop: 10,
    flexDirection: "row",
    alignItems: "flex-end",
    justifyContent: "center",
    paddingBottom: 20,
  },
});
